package com.definity.toolkit.ui.widget.support;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Calendar;
import java.util.Date;

import com.definity.toolkit.ui.style.Style;

public class CalendarSupport {

	private final PropertyChangeSupport support = new PropertyChangeSupport(this);
	private final Calendar baseDate;
	
	private Style normalStyle;
	private Style weekendStyle;
	private Style selectedStyle;

	private Date dateSelected;
	private Style anotherMonthStyle;

	public CalendarSupport() {
		this(Calendar.getInstance());
		
		setDateSelected(Calendar.getInstance().getTime());
	}
	
	public CalendarSupport(Calendar baseDate) {
		this.baseDate = baseDate;
		this.baseDate.set(Calendar.HOUR_OF_DAY, 0);
		this.baseDate.set(Calendar.MINUTE, 0);
		this.baseDate.set(Calendar.SECOND, 0);
	}

	public void addPropertyChangeListener(PropertyChangeListener listener) {
		support.addPropertyChangeListener(listener);
	}

	public void removePropertyChangeListener(PropertyChangeListener listener) {
		support.removePropertyChangeListener(listener);
	}
	
	public Style getNormalStyle() {
		return normalStyle;
	}

	public void setNormalStyle(Style normalStyle) {
		this.normalStyle = normalStyle;
	}

	public Style getWeekendStyle() {
		return weekendStyle;
	}

	public void setWeekendStyle(Style weekendStyle) {
		this.weekendStyle = weekendStyle;
	}

	public Style getSelectedStyle() {
		return selectedStyle;
	}

	public void setSelectedStyle(Style selectedStyle) {
		this.selectedStyle = selectedStyle;
	}

	public Style getAnotherMonthStyle() {
		return anotherMonthStyle;
	}
	
	public void setAnotherMonthStyle(Style anotherMonthStyle) {
		this.anotherMonthStyle = anotherMonthStyle;
	}
	
	public Calendar getBaseDate() {
		return (Calendar) baseDate.clone();
	}
	
	public Date getDateSelected() {
		return dateSelected;
	}
	
	public void setDateSelected(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		Date oldDateSelected = this.dateSelected;
		this.dateSelected = c.getTime();
		
		support.firePropertyChange("dateSelected", oldDateSelected, date);
	}

	public Style getStyle(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		
		date = calendar.getTime();
		
		int day = calendar.get(Calendar.DAY_OF_WEEK);
		int month = calendar.get(Calendar.MONTH);

		if (date.equals(dateSelected)) {
			return selectedStyle;
		} else if (month != baseDate.get(Calendar.MONTH)) {
			return anotherMonthStyle;
		} else if (day == Calendar.SUNDAY) {
			return weekendStyle;
		} else {
			return normalStyle;
		}
	}

}
